<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Db;

class Fuyou extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function post1($postData)
    {
        $url = "https://aipay-cloud.fuioupay.com/aggregatePay/preCreate";
        $jsonData = json_encode($postData);
        // dump($url);die;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json'
        ));
        // 发送请求并获取响应
        $response = curl_exec($ch);

        return $response;
    }
    //微信
    public function wx($res,$pay)
    {
        //②、统一下单
        $dizhi = 'http://'.$this->request->host();
        $notifyUrl = $dizhi."/index/Fuyou/wx_hd/id/".$res['id'].'/type/'.$res['type'].'/channel_id/'.$pay['id'];// 替换为您的支付回调通知地址
        // // 微信支付配置
        $json = json_decode($pay['json']);
        $mchId = $json->mid; // 替换为您的商户号
        $apiKey = $json->key; // 替换为您的API密钥
        $order = $json->order; // 替换为您的API密钥
        // 构建统一下单请求参数
        $data = $this->buildUnifiedOrderData( $mchId, $apiKey, $notifyUrl,$res,$order);
        $result = $this->post1($data);
        $result = json_decode($result, true);
        if (!$result || !isset($result['qr_code'])) {  //失败处理
            dump($result['result_msg']);die;
        } else {    //成功处理
            $jsApiParameters = $result['qr_code'];
            return $jsApiParameters;
        }
    }

    // 构建统一下单请求参数
    public function buildUnifiedOrderData( $mchId, $apiKey, $notifyUrl,$res,$order)
    {
        $data = array(
            "mchnt_cd" => $mchId,//富友分配的商户号,例：0002900F0313432
            "order_type"=>"WECHAT",
            "order_amt"=>strval($res['main_free']*100),
            "mchnt_order_no" => $order.$this->third_order_id(), // 替换为您的订单号
            "txn_begin_ts" => date('YmdHis',time()),
            "goods_des"=>'订单',
            "term_id"=>$this->generateRandomString(8),
            "term_ip"=>$_SERVER['REMOTE_ADDR'],
            "notify_url" => $notifyUrl,
            "random_str"=>$this->generateOrderNumber(),
            "version"=>"1.0",
        );
        $data["sign"] = $this->generateSignature($apiKey, $data); // 生成签名
        return $data;
    }

    function generateRandomString($length = 8) {
        // 生成随机字节串
        $bytes = random_bytes($length);
        // 转换为十六进制表示
        $hex = bin2hex($bytes);
        // 确保长度为8字符
        $randomString = substr($hex, 0, $length * 2);
        // 处理生成的随机字符串，使其既包含数字也包含字母
        $count = strlen($randomString);
        $newString = '';
        for ($i = 0; $i < $count; $i++) {
            $char = $randomString[$i];
            // 如果是数字，则保持不变
            if (ctype_digit($char)) {
                $newString .= $char;
            } else {
                // 如果是字母，则转换为小写
                $newString .= chr(ord(strtolower($char)) + 4);
            }
        }
        // 最后，将字符串截断到原始长度，并转换为32位表示的十六进制数
        return substr(bin2hex(str_replace(' ', '', chunk_split($newString, 8, ' '))), 0, $length * 2);
    }
    function third_order_id() {
        $timestamp = time(); // 当前时间戳
        $random = mt_rand(1000, 9999); // 生成一个 4 位随机数
        $orderNumber = $timestamp . $random; // 拼接时间戳和随机数
        return $orderNumber;
    }
    function generateOrderNumber() {
        $timestamp = time(); // 当前时间戳
        $array1 = array(0,1,2,3,4,5,6,7,8,9,'q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m','Q','W','E','R','T','Y','U','I','O','P','M','N','B','V','C','X','Z','A','S','D','F','G','H','J','K','L');
        $i= 0;
        $str = null;
        while ( $i<= 21) {
            $str .= $array1[array_rand($array1,1)];
            $i++;
        }
        $orderNumber = $timestamp . $str; // 拼接时间戳和随机数
        return $orderNumber;
    }
    // 生成请求的签名
    public function generateSignature($apiKey, $data)
    {
        $signData = '';
        foreach ($data as $key => $value) {
            $signData .= $value . '|';
        }
        $signData .= $apiKey;
        return hash('MD5', $signData); // 使用HMAC-SHA256进行签名
    }
    //微信异步通知
    public function wx_hd()
    {
        $xml_data = file_get_contents('php://input');
        Log::record('回调参数', $xml_data);
        $result = json_decode($xml_data, true);
        Db::startTrans();
        try{
            $params = request()->param();
            //修改数据
            $up = Db::name('list_one')
                ->where(['id'=>$params['id']])
                ->update([
                    'jiaofei'=>2,
                    'jiaofei_price'=>$result['reserved_settlement_amt']/100,
                    'trade_no'=>$result['mchnt_order_no'],
                    'out_trade_no'=>$result['reserved_channel_order_id'],
                    'jiaofei_time'=>date("Y-m-d H:i:s",time()),
                    'feiyong_type'=>$params['type'],
                    'type'=>$params['type']
                ]);
            $model = new Index();
            $channel_id = $params['channel_id'];
            $sid = $model->num($params['id'],$channel_id);
            // 提交事务
            Db::commit();
            db('ceshi')->insert(['text'=>$params['id'].'|'.date("Y-m-d H:i:s",time()).'|'.$result['reserved_channel_order_id'].'|']);
            return '1';
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $c = $e->getMessage();
            db('ceshi')->insert(['text'=>'111'.date("Y-m-d H:i:s",time()).$c]);
            $returnData = [
                "code" => "ERROR",
                "message" => "回调失败"
            ];
        }
    }



}